export function treeToArrayOptimized(tree, childrenKey = "children") {
  const result = [];
  let index = 0;

  console.log(tree, "11");

  function traverse(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      const node = nodes[i];
      const children = node[childrenKey];

      // 直接操作结果数组，避免对象解构的性能开销
      const item = {};

      for (const key in node) {
        if (key !== childrenKey) {
          item[key] = node[key];
        }
      }

      result[index++] = item;

      if (children && children.length > 0) {
        traverse(children);
      }
    }
  }

  traverse(tree);

  return result;
}

export function removeEmptyChildren(data) {
  // 处理数组
  if (Array.isArray(data)) {
    return data.map((item) => removeEmptyChildren(item));
  }

  // 处理对象
  if (typeof data === "object" && data !== null) {
    const result = { ...data };

    // 如果有 children 属性
    if (result.children) {
      // 递归处理 children
      result.children = removeEmptyChildren(result.children);

      // 如果处理后的 children 是空数组，则删除这个属性
      if (Array.isArray(result.children) && result.children.length === 0) {
        delete result.children;
      }
    }

    return result;
  }

  return data;
}
